<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item label="选择sku">
        <select-sku-by-name-component @update-sku-id="updateSkuId"
                                      ref="selectSkuByNameComponentRef"></select-sku-by-name-component>
      </el-form-item>
      <el-form-item label="选择仓库">
        <select-ware-by-name-component @update-ware-id="updateWareId"
                                       ref="selectWareByNameComponentRef"></select-ware-by-name-component>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="dataForm.status" placeholder="请选择">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="clearCondition">清除条件</el-button>
        <el-button @click="getDataList()" type="success">查询</el-button>
        <el-button v-if="isAuth('wms:purchasedetail:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button type="info" @click="mergePurchaseItemToPurchaseMenu" :disabled="dataListSelections.length<=0">
          合并选中的采购需求到采购单中
        </el-button>
        <el-button v-if="isAuth('wms:purchasedetail:delete')" type="danger" @click="deleteHandle()"
                   :disabled="dataListSelections.length <= 0">批量删除
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="id"
        header-align="center"
        align="center"
        label="id">
      </el-table-column>
      <el-table-column
        prop="purchaseId"
        header-align="center"
        align="center"
        label="采购单id">
      </el-table-column>
      <el-table-column
        prop="skuName"
        header-align="center"
        align="center"
        label="采购商品名称">
      </el-table-column>
      <el-table-column
        prop="skuNum"
        header-align="center"
        align="center"
        label="采购数量">
      </el-table-column>
      <el-table-column
        prop="skuPrice"
        header-align="center"
        align="center"
        label="采购金额">
      </el-table-column>
      <el-table-column
        prop="wareName"
        header-align="center"
        align="center"
        label="仓库名称">
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        label="状态">
        <!--        [0新建，1已分配，2正在采购，3已完成，4采购失败]-->
        <template slot-scope="slot">

<!--          <el-tag :type="parseStringStatusToType(slot.row.status)">{{ slot.row.status }}</el-tag>-->
          <el-tag :type="statusOptions[slot.row.status].type">{{ statusOptions[slot.row.status].label }}</el-tag>
          <!--          <el-tag v-if="slot.row.status==0">新建</el-tag>
                    <el-tag v-if="slot.row.status==1" type="success">已分配</el-tag>
                    <el-tag v-if="slot.row.status==2" type="info">正在采购</el-tag>
                    <el-tag v-if="slot.row.status==3" type="warning">已完成</el-tag>
                    <el-tag v-if="slot.row.status==4" type="danger">采购失败</el-tag>-->
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

    <!--    合并到采购单中-->
    <el-dialog title="合并采购需求" :visible.sync="dialogFormVisible">
      <el-form>
        <el-form-item label="选择采购单负责人" label-width="200">
          <select-and-search-purchase-component
            @update-purchase-id="updatePurchaseId"></select-and-search-purchase-component>
        </el-form-item>
        <el-form-item label="采购需求" label-width="200">
          <el-checkbox-group v-model="purchaseItemNameList">
            <el-checkbox :label="skuName" v-for="(skuName,index) in purchaseItemNameListForSelect"
                         :key="index"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmToMergePurchasing">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from './purchaseDetailComponent/purchasedetail-add-or-update'
import selectAndSearchPurchaseComponent from './purchaseComponent/selectAndSearchPurchaseComponent'
import purchaseDetailApi from '../../../api/ware/purchaseDetailApi'
import purchaseApi from '../../../api/ware/purchaseApi'

export default {
  components: {
    AddOrUpdate,
    'select-ware-by-name-component': () => import('./wareInfoComponent/select-ware-by-name-component'),
    'select-sku-by-name-component': () => import('./skuComponent/select-sku-by-name-component'),
    selectAndSearchPurchaseComponent
  },
  data () {
    return {
      dataForm: {
        key: null,
        skuId: null,
        wareId: null,
        status: null,
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      //采购状态[0新建，1已分配，2正在采购，3已完成，4采购失败]
      statusOptions: [
        {
          label: '新建',
          value: 0,
          type: ''
        }, {
          label: '已分配',
          value: 1,
          type: 'success'
        }, {
          label: '正在采购',
          value: 2,
          type: 'info'
        }, {
          label: '已完成',
          value: 3,
          type: 'warning'
        }, {
          label: '采购失败',
          value: 4,
          type: 'danger'
        }
      ],
      dialogFormVisible: false,
      purchaseId: null,
      purchaseItemNameList: [],
      purchaseItemNameListForSelect: null
    }
  },

  activated () {
    this.getDataList()
  },
  methods: {
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl(`/wms/purchasedetail/list/${this.pageIndex}/${this.pageSize}`),
        method: 'post',
        data: this.dataForm
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/wms/purchasedetail/deleteBatch'),
          method: 'put',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },

    updateSkuId (skuId) {
      this.dataForm.skuId = skuId
    },

    updateWareId (wareId) {
      this.dataForm.wareId = wareId
    },

    clearCondition () {
      this.dataForm = {
        key: null,
        skuId: null,
        wareId: null,
        status: null,
      }
      this.$refs.selectWareByNameComponentRef.dataForm.wareId = null
      this.$refs.selectSkuByNameComponentRef.dataForm.skuId = null
      this.getDataList()
    },

    mergePurchaseItemToPurchaseMenu () {
      console.log('选中的采购需求是是', this.dataListSelections)
      this.dialogFormVisible = true
    },

    updatePurchaseId (val) {
      // console.log("负责人已更新",val);
      this.purchaseId = val
    },

    // 确认合并采购需求
    async confirmToMergePurchasing () {

      let afterCheckBox = this.dataListSelections.filter(row => {

        /**
         * 过滤调用用户第二次没有选中的采购需求
         * */
        for (let i = 0; i < this.purchaseItemNameList.length; i++) {
          if (row.skuName === this.purchaseItemNameList[i]) {
            return true
          }
        }
      })

      console.log('经过用户二次筛选之后剩下的选中节点是', afterCheckBox)



      if (afterCheckBox.length === 0) {
        this.$message({
          type: 'info',
          message: '本次没有采购需求被添加到采购表中'
        })
        return
      }

      let purchaseDetailListForUpdateArray = afterCheckBox.map(row => {
        return {
          id: row.id,
          purchaseId: this.purchaseId,
          status: 1, // 更新采购单的状态为已分配
          wareId:row.wareId
        }
      })

      console.log('最终发送的数据是', purchaseDetailListForUpdateArray);

      if (this.purchaseId == null) {
        /*this.$message({
          type:'warning',
          message:'请选择采购单的负责人'
        });*/
        this.createPurchasingMenuAndMergeToIt(purchaseDetailListForUpdateArray)

        return
      }

      // let p = await purchaseApi.bindPurchaseDetailToPurchaseId(purchaseDetailListForUpdateArray)

      purchaseApi.bindPurchaseDetailToPurchaseId(purchaseDetailListForUpdateArray).then(()=>{
        this.$message({
          type: 'success',
          message: `${this.purchaseItemNameList.join(',')} 已经绑定采购单`
        })

        this.dialogFormVisible = false

        this.getDataList()
      }).catch(({response})=>{

        /*console.log(response)
        this.$message({
          type:"error",
          message:response.data.message
        });*/
      })


    },

    createPurchasingMenuAndMergeToIt (purchaseDetailListForUpdateArray) {
      this.$confirm(`没有选中采购单, 系统将为【${this.purchaseItemNameList.join(',')}】自动创建一个采购单，是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        // console.log("你好")

        /*let p = async () => await purchaseApi.createPurchasingMenuAndMergeToIt(purchaseDetailListForUpdateArray);

        let purchaseId = p.data.purchaseEntity.id;*/

        purchaseApi.createPurchasingMenuAndMergeToIt(purchaseDetailListForUpdateArray).then(({data})=>{


          this.$message({
            type: 'success',
            message: `【${this.purchaseItemNameList.join(',')}】已为其分配采购单 ：${data.purchase.id} !`
          });

          this.dialogFormVisible = false

          this.getDataList()

        })




      }).catch(() => {

        this.$message({
          type: 'info',
          message: '已取消创建采购单'
        })
      })
    },

    parseStringStatusToType(statusStr){
      for (let i = 0; i < this.statusOptions.length; i++) {
        if(this.statusOptions[i].label===statusStr){
          return this.statusOptions[i].type
        }
      }

  },

  },
  watch: {
    dataListSelections (val) {
      // 用作checkBox 保存选中的数值用
      this.purchaseItemNameList = val.map(row => {
        return row.skuName
      }).filter(skuName => {
        return skuName != null
      })

      // 用于checkBox选择用
      this.purchaseItemNameListForSelect = this.purchaseItemNameList
    }
  },

}
</script>
